<?php

namespace App\Http\Controllers\Admin;

use App\Models\ResourceVideoGatherInfo;
use App\Models\ResourceVideoInfo;
use App\Validate\ResourceVideoGatherInfoValidate;
use Illuminate\Support\Facades\DB;

/**
 * 视频集数管理
 */
class ResourceVideoGatherManageController extends CommonController
{
    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->validate = new ResourceVideoGatherInfoValidate();
        $this->model = new ResourceVideoGatherInfo();
    }

    /**
     * 获取音频资源
     * @param keywords 检索条件
     * @param video_id 视频id
     * @param page int 当前页
     * @param limit int 分页大小
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('lists')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $limit = $this->request->input('limit', 10);
        $page = $this->request->input('page', 1);
        $res = $this->model->lists($this->request->all());
        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['size'] = format_bytes($val['size']);
        }
        //增加序号
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
        $res = $this->disPageData($res);
        return $this->returnApi(200, '获取成功', true, $res);
    }

    /**
     * 详情
     * @param gather_id int 集数id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->gather_id);
        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        $res = $res->toArray();
        $res['size'] = format_bytes($res['size']);
        return $this->returnApi(200, "获取成功", true, $res);
    }

    /**
     * 新增
     * @param video_id 音频id
     * @param gather_name string 音频名字
     * @param gather_src string 音频章节地址
     * @param size string 字节大小 单位字节
     * @param img string 封面图片
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $gather_src = $this->request->gather_src;

        $findWhere[] = ['video_id', '=', $this->request->video_id];
        $is_exists = $this->model->nameIsExists($this->request->gather_name, 'gather_name', null, 1, $findWhere);

        if ($is_exists) {
            return $this->returnApi(202, "该名称已存在");
        }
        DB::beginTransaction();
        try {
            //如果是临时图片，移动到指定位置
            if ($gather_src  && strpos($gather_src, 'temp_video') !== false) {
                $move_file = $this->moveUploadedFile($gather_src,  'resource_video');
                if (!$move_file) {
                    throw new \Exception('音频保存失败');
                }
                $this->request->merge(['gather_src' => $move_file]); //重置音频地址
            }
            $postfix = explode('.', $this->request->gather_src);
            $this->request->merge(['postfix' => end($postfix)]);
            $this->model->addResource($this->request->all());

            //更新资源总字节
            $resourceVideoInfoModel = new ResourceVideoInfo();
            $resourceVideoInfoModel->updateResourceSize($this->request->video_id);

            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "新增失败");
        }
    }

    /**
     * 修改
     * @param gather_id int 集数id
     * @param video_id int 视频id
     * @param gather_name string 音频名字
     * @param gather_src string 音频章节地址
     * @param size string 字节大小 单位字节
     * @param img string 封面图片
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $gather_src = $this->request->gather_src;

        $findWhere[] = ['video_id', '=', $this->request->video_id];
        $is_exists = $this->model->nameIsExists($this->request->gather_name, 'gather_name', $this->request->gather_id, 1, $findWhere);

        if ($is_exists) {
            return $this->returnApi(202, "该名称已存在");
        }

        $res = $this->model->detail($this->request->gather_id);
        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        $old_video = $res->gather_src;
        DB::beginTransaction();
        try {
            //如果是临时图片，移动到指定位置
            if ($gather_src  && strpos($gather_src, 'temp_video') !== false) {
                $move_file = $this->moveUploadedFile($gather_src,  'resource_video');
                if (!$move_file) {
                    throw new \Exception('音频保存失败');
                }
                $this->request->merge(['gather_src' => $move_file]); //重置音频地址
            }
            $postfix = explode('.', $this->request->gather_src);
            $this->request->merge(['postfix' => end($postfix)]);
            $this->model->changeResource($this->request->all());

            //删除旧资源
            if ($old_video != $this->request->gather_src) {
                $this->deleteFile($old_video);
            }

            //更新资源总字节
            $resourceVideoInfoModel = new ResourceVideoInfo();
            $resourceVideoInfoModel->updateResourceSize($res->id);

            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "修改失败");
        }
    }

    /**
     * 删除
     * @param gather_id int 集数id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        DB::beginTransaction();
        try {
            $this->model->del($this->request->gather_id);
            //更新资源总字节
            $video_id = $this->model->where('id', $this->request->gather_id)->value('video_id');
            $resourceVideoInfoModel = new ResourceVideoInfo();
            $resourceVideoInfoModel->updateResourceSize($video_id);

            DB::commit();
            return $this->returnApi(200, "删除成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 排序
     * content json格式数据  [{"id":1,"sort":2},{"id":2,"sort":2},{"id":3,"sort":3},{"id":4,"sort":4},{"id":5,"sort":5}]   第一个 sort 最大
     */
    public function sortChange()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('sort_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $content = $this->request->input('content', '');
        if (empty($content)) {
            return $this->returnApi(201, "参数传递错误");
        }
        $content = json_decode($content, true);

        DB::beginTransaction();
        try {
            foreach ($content as $key => $val) {
                $this->model->where('id', $val['id'])->update(['sort' => $val['sort']]);
            }
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
